package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {

    //注入发票service
    @Reference
    private InvoiceService invoiceService;

    //注入装箱service
    @Reference
    private PackingService packingService;

    //注入报运单service
    @Reference
    private ExportService exportService;

    //注入购销合同service
    @Reference
    private ContractService contractService;

    //注入委托service
    @Reference
    private ShippingService shippingService;


    /**
     * 进入发票列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        InvoiceExample invoiceExample = new InvoiceExample();
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(invoiceExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/invoice/invoice-list";

    }


    /**
     * 生成发票
     */

    @RequestMapping("/invoice")
    public String invoice(String id) {
        Invoice invoice = new Invoice();
        //查出装箱信息，拿报运合同 跟 发票金额
        Packing packing = packingService.selectByPrimaryKey(id);

        //报运合同号
        invoice.setScNo(packing.getExportNos());
        //发票金额
        invoice.setInvoiceMoney(packing.getPackingMoney());

        //定义一个贸易条款
        String tradeTerms = "";

        //遍历拿到贸易条款
        String exportIds = packing.getExportIds();
        String[] exportId = StringUtils.split(exportIds, ',');

        //购销合同id
        String contractIds = "";

        if (exportId.length != 0) {
            //遍历报运单号查购销合同号
            for (String eId : exportId) {
                Export export = exportService.findById(eId);
                contractIds += export.getContractIds() + ",";
            }
        } else {
            Export export = exportService.findById(exportIds);
            contractIds += export.getContractIds() + ",";
        }



        List<Contract> contractList;
        //拿到每个购销合同id
        String[] contractId = StringUtils.split(contractIds, ',');
        if (contractId.length != 0) {
            ContractExample contractExample = new ContractExample();
            contractExample.createCriteria().andIdIn(Arrays.asList(contractId));
            contractList = contractService.findAll(contractExample);
        } else {
            ContractExample contractExample = new ContractExample();
            contractExample.createCriteria().andIdIn(Arrays.asList(contractIds));
            contractList = contractService.findAll(contractExample);
        }



        //拿到贸易条款
        for (Contract contract : contractList) {
            tradeTerms += contract.getTradeTerms() + " ";
        }

        invoice.setTradeTerms(tradeTerms);

        request.setAttribute("invoice",invoice);
        request.setAttribute("id",id);

        return "cargo/invoice/invoice-toInvoice";
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 保存功能edit
     */
    @RequestMapping("/edit")
    public String edit(Invoice invoice, MultipartFile pp) throws Exception {
        Shipping shipping = shippingService.findBySOId(invoice.getInvoiceId());
        invoice.setDestinationPort(shipping.getPortOfLoading()); //目的港
        invoice.setConsignee(shipping.getConsignee());         //收货人
        invoice.setShipmentPort(shipping.getPortOfLoading());     //装运港
        invoice.setStatus(0);
        if (pp != null) {
            if (pp.getSize() > 0) {
                //如果大小大于0则是有上传,把照片保存七牛云上
                String url = fileUploadUtil.upload(pp);
                //把图片的url保存到货物中
                invoice.setPickupPhoto("http://" + url);
            }
        }

        invoiceService.save(invoice);

        return "redirect:/cargo/invoice/list.do";
    }


    /**
     * 判断是否可以删除
     */
    @RequestMapping("/ifDelete")
    @ResponseBody
    public void ifDelete(String id) throws IOException {
        PrintWriter out = response.getWriter();

        Invoice invoice = invoiceService.findById(id);
        if (invoice.getStatus() == 0) {
            out.print("true");
        } else {
            out.print("false");
        }
    }
    /**
     * 删除装箱单
     * /cargo/invoice/delete.do?id=08426ad5-c6e4-47d0-89eb-a875e2023a73
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        invoiceService.delete(id);
        return "redirect:/cargo/invoice/list.do";
    }


    /**
     * 查看发票
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        Invoice invoice = invoiceService.findById(id);

        request.setAttribute("invoice",invoice);
        return "cargo/invoice/invoice-view";
    }


    /**
     * 下载pdf
     */

    @RequestMapping("/download")
    @ResponseBody
    public void exportPdf(String id) throws Exception {
        //设置响应头
        response.setHeader("content-disposition","attachment;filename=发票表.pdf");

        //1. 读取模板
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/invoice.jasper");

        //2. 将模板与数据结合得到JasperPrint对象
        /*
            fillReport(InputStream inputStream, Map<String, Object> parameters, JRDataSource dataSource)
                    inputStream: 模板的输入流
                    parameters: 不需要遍历参数，填充的参数
                    dataSource: 需要遍历的集合数据存储到数据源
         */

        //3. 根据id查找到报运单
        Invoice invoice = invoiceService.findById(id);

        //4. 把export对象转换为map
        Map<String, Object> map = BeanMapUtils.beanToMap(invoice);



        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream,map,new JREmptyDataSource());

        //3. 把pdf输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }

}
